package com.gao.shiro.jwt.filter;

import com.gao.shiro.jwt.token.MyToken;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.web.filter.authc.AuthenticationFilter;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

/**
 * @Description TODO  shiro的自定义拦截器  拦截token 并执行校验  做出相应的操作
 * @Author anshenghui
 * @Date 2020/2/11 14:14
 * @Version 1.0
 */
@Slf4j
public class JwtFilter extends AuthenticationFilter {

    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) {
        try {
            myLogin(request, response);
            return true;
        } catch (Exception e) {
            log.info("token存在异常，请重新登录！错误信息-----");
            throw new AuthenticationException("token存在异常，请重新登录", e);
        }
    }

    private boolean myLogin(ServletRequest request, ServletResponse response) throws Exception {
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        log.info("拦截路径：" + httpServletRequest.getRequestURL());
        //获取请求头里面的token
        String token = httpServletRequest.getHeader("Authorization");
//        String token = "sdasdasd3453432";
        MyToken myToken = new MyToken(token);
        //提交给自定义的realm  进行验证
        SecurityUtils.getSubject().login(myToken);
        return true;
    }
}
